
import { HashRouter,BrowserRouter,Route,Routes,Link,useRoutes,useNavigate } from "react-router-dom";
import {constantRoutes} from "@/pages/constant"
import {useEffect,useMemo} from 'react'
import {useSelector,useDispatch} from 'react-redux'
import { getInfo } from "./store/action";
import {generateRoutes} from "@/store/permission"
import { asyncRoutes } from "@/pages/index.jsx";
function Page(){
    const dispatch = useDispatch()
    const navigator = useNavigate();
    const {token,roles,accessRoutes} = useSelector(state=>state.user)
    //监听token变化
    useEffect(()=>{
        // console.log("token=======" ,token);
        // dispatch(getInfo())
        if (token) {
            dispatch(getInfo())
          } else {
            navigator("/login", { replace: true })
          }
    },[token])
    useEffect(()=>{
        console.log(roles);
        if(roles &&roles.length >0){
           // roles是一个数组，里面包含了角色，配合路由总表+算法，生成当前用户可以访问的路由规则们
             dispatch(generateRoutes(asyncRoutes,roles))
        }
    },[roles])
    useEffect(()=>{
        if (accessRoutes && accessRoutes.length > 0) {
            navigator("/dashboard", { replace: true })
          }
    },[accessRoutes])
    const routes = useMemo(() => {
        const result = [...constantRoutes];
        result[0].children = accessRoutes
        return result;
      }, [accessRoutes]);
    //   console.log('所有的路由规则',routes);
    const element = useRoutes(constantRoutes)
    return element
}
export default Page